package org.example.com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.com.Bean.Book;
import org.example.com.Bean.User;
import org.example.com.exception.userRemoveException;
import org.example.com.exception.userSaveException;
import org.example.com.exception.userUpdateException;
import org.example.com.mapper.BookMapper;
import org.example.com.service.BookService;
import org.example.com.util.JsonResult;
import org.example.com.util.RecultTool;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Override
    public JsonResult findBook(){
    return RecultTool.success(list());
}
    @Override
    public JsonResult findBook(int page){
        Page<Book> p= Page.of(page, 10);
        List<Book> list=list(p);
        p.setRecords(list);
        return RecultTool.success(p);
    }
    public JsonResult findByBookName(String name,int page) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        //设置条件
        wrapper.like("name", name);
        Page<Book> p1= Page.of(page, 10);
        List<Book> list = list(p1, wrapper);
        //查询
        p1.setRecords(list);
        return RecultTool.success(p1);
    }

    @Override
    public JsonResult findById(String id) {
        Book byId = getById(id);
        return RecultTool.success(byId);
    }

    @Override
    public JsonResult saveBook(Book book) {
        boolean save = save(book);
        if (!save) {
            throw new userSaveException("添加图书失败");
        }
        return RecultTool.success("success");
    }
    @Override
    public JsonResult deleteBook(String id) {
        boolean save = removeById(id);
        if (!save) {
            throw new userUpdateException("删除图书失败");
        }
        return RecultTool.success("success");
    }

    @Override
    public JsonResult updateBook(Book book) {
        boolean save = updateById(book);
        if (!save) {
            throw new userUpdateException("修改用图书失败");
        }
        return RecultTool.success("success");
    }
    @Override
    public JsonResult updateBookStatus(String id, int status) {
        UpdateWrapper<Book> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("status", status);
        boolean b = update(wrapper);
        if (!b) {
            throw new userRemoveException("修改状态失败");
        }
        return RecultTool.success("success");
    }
}